package com.cloud.weichat;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import net.sf.json.JSONObject;

/**
 * 素材
 *
 * @author
 * @create 2017-09-22 16:42
 **/

public class Material {

    public static void main(String[] args) {
        //企业号id
        String corpid = "wwc868836095c414e0";
        //企业号密钥
        String serect = "hcOy6B7L2reDl0Wp11fyhX3yHQkNtrfjJ6k3eme1Mg8";
        //token获取地址
        String accesstokenurl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SERCRET";
        accesstokenurl = accesstokenurl.replace("ID", corpid).replace("SERCRET", serect);
        //获取token
        JSONObject accesstoken = HttpRequest(accesstokenurl, "GET", null);
        String token = accesstoken.getString("access_token");
        String filePath = "http://img4.imgtn.bdimg.com/it/u=805849949,3076359299&fm=206&gp=0.jpg";
        //上传素材文件
        JSONObject result = uploadMedia(token, "image", filePath);
        System.out.println(result);
    }

    /**
     * 上传媒体文件
     *
     * @param accessToken  接口访问凭证
     * @param type         媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)
     * @param media        form-data中媒体文件标识，有filename、filelength、content-type等信息
     * @param mediaFileUrl 媒体文件的url
     *                     上传的媒体文件限制
     *                     图片（image）:1MB，支持JPG格式
     *                     语音（voice）：2MB，播放长度不超过60s，支持AMR格式
     *                     视频（video）：10MB，支持MP4格式
     *                     普通文件（file）：20MB
     */
    public static JSONObject uploadMedia(String accessToken, String type, String mediaFileUrl) {
        JSONObject jsonObject = null;
        // 拼装请求地址
        String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
        uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);
        // 定义数据分隔符
        String boundary = "------------7da2e536604c8";
        try {
            URL uploadUrl = new URL(uploadMediaUrl);
            HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
            uploadConn.setDoOutput(true);
            uploadConn.setDoInput(true);
            uploadConn.setRequestMethod("POST");
            // 设置请求头Content-Type
            uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            // 获取媒体文件上传的输出流
            OutputStream outputStream = uploadConn.getOutputStream();
            URL mediaUrl = new URL(mediaFileUrl);
            HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
            meidaConn.setDoOutput(true);
            meidaConn.setRequestMethod("GET");
            // 从请求头中获取内容类型
            String contentType = meidaConn.getContentType();
            // 根据内容类型判断文件扩展名
            String fileExt = ".jpg";
            // 请求体开始
            outputStream.write(("--" + boundary + "\r\n").getBytes());
            outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
            outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());
            // 获取媒体文件的输入流
            BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1) {
                // 将媒体文件写到输出流（往微信服务器写数据）
                outputStream.write(buf, 0, size);
            }
            // 请求体结束
            outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
            outputStream.close();
            bis.close();
            meidaConn.disconnect();
            // 获取媒体文件上传的输入流
            InputStream inputStream = uploadConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            StringBuffer buffer = new StringBuffer();
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            uploadConn.disconnect();
            // 使用JSON-lib解析返回结果
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (Exception e) {
            //日志处理等，请自行完善。
        }
        return jsonObject;
    }

    public static JSONObject HttpRequest(String requestUrl, String requestMethod,
                                         String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        OutputStream out = null;
        InputStream input = null;
        InputStreamReader inputReader = null;
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        try {
            // 建立连接
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 设置http头部信息
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestMethod(requestMethod);
            // 写入消息实体
            if (outputStr != null) {
                out = connection.getOutputStream();
                out.write(outputStr.getBytes("UTF-8"));
            }
            // 流处理
            input = connection.getInputStream();
            inputReader = new InputStreamReader(input, "UTF-8");
            reader = new BufferedReader(inputReader);
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
            String re = buffer.toString();
            jsonObject = JSONObject.fromObject(re);
        } catch (Exception e) {
            //日志处理等，请自行实现
            e.printStackTrace();
        } finally {
            try {
                if (outputStr != null) {
                    out.close();
                }
                // 关闭连接、释放资源
                if (reader != null) {
                    reader.close();
                }
                if (inputReader != null) {
                    inputReader.close();
                }
                if (input != null) {
                    input.close();
                }
                input = null;
                connection.disconnect();
            } catch (Exception e) {
                //日志处理等，请自行实现
                e.printStackTrace();
            }
        }
        return jsonObject;
    }


}

